﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;

using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Authorization;
using Api_Backstage.Code;

namespace Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddMvc(options =>
            {
                // 注入检查用户登录状态 如未登录则通过控制器直接返回
                options.Filters.Add(typeof(AuthorizationFilter));
                options.Filters.Add(typeof(WebApiResultMiddleware));
                options.RespectBrowserAcceptHeader = true;
            });
            // services.AddHttpContextAccessor();
            // 注入依赖
            services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            // 注入sessiong
            #region 使用Redis保存Session
            var redisConn = Configuration["WebConfig:Redis:Connection"];
            var redisInstanceName = Configuration["WebConfig:Redis:InstanceName"];
            //Session 过期时长分钟
            var sessionOutTime = Configuration.GetValue<int>("WebConfig:SessionTimeOut", 30);

            //var redis = StackExchange.Redis.ConnectionMultiplexer.Connect(redisConn);
            //services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Test-Keys");
            // services.AddDistributedRedisCache(option =>
            //     {
            //         //redis 连接字符串
            //         option.Configuration = redisConn;
            //         //redis 实例名
            //         option.InstanceName = redisInstanceName;
            //     }
            // );
            // //添加Session并设置过期时长
            // services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(sessionOutTime); });
            #endregion
            // services.AddDistributedMemoryCache();
            // services.AddSession(options =>
            // {
            //     // Set a short timeout for easy testing.
            //     options.IdleTimeout = TimeSpan.FromSeconds(10);
            //     options.Cookie.HttpOnly = true;
            //     // Make the session cookie essential
            //     options.Cookie.IsEssential = true;
            // });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "聊天API",
                    Description = "聊天API",
                    TermsOfService = "None",
                    Contact = new Contact
                    {
                        Name = "Shayne Boyer",
                        Email = string.Empty,
                        Url = "https://twitter.com/spboyer"
                    },
                    License = new License
                    {
                        Name = "Use under LICX",
                        Url = "https://example.com/license"
                    }
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var str = AppContext.BaseDirectory;
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                var xmlPath1 = Path.Combine(AppContext.BaseDirectory, "Model.xml");
                c.IncludeXmlComments(xmlPath);
                c.IncludeXmlComments(xmlPath1);
                c.OperationFilter<HttpHeaderOperation>();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            // 注入httpscontext
            Utils.HttpContextClass.ServiceProvider = app.ApplicationServices;
            // 捕获全局错误
            app.UseMiddleware(typeof(ExceptionHandlerMiddleWare));
            // 注入swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1 doc");
            });
            // 注入websocket
            app.UseWebSockets();
            app.UseMiddleware<BLL.Wapper.WebSocketWapper>();
            app.UseHttpsRedirection();
            // app.UseSession();
            app.UseMvc();
        }
    }
}
